package top.xiaoshuaila.moments.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.xiaoshuaila.moments.mapper.UserMapper;
import top.xiaoshuaila.moments.pojo.Users;

import java.util.concurrent.TimeUnit;

@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //重写loadUserByusername通过username获取对应的继承了userdetail接口的admin对象
        Users users ;
        if(redisTemplate.opsForValue().get("user-"+username)==null)
        {
            users=userMapper.getWithName(username);
            users.setPassword("");
            redisTemplate.opsForValue().set("user-"+username, JSON.toJSONString(users),24, TimeUnit.HOURS);
        }
        else {
            users=JSON.parseObject(redisTemplate.opsForValue().get("user-"+username),Users.class);
        }
        redisTemplate.opsForValue().set("id-"+users.getId(), "user-"+username,24, TimeUnit.HOURS);
        if(users!=null)return users;
        throw new UsernameNotFoundException("用户名或者密码不正确");
    }
}